#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <sys/select.h>
#include <cstdlib>

// 保存原始终端设置以在退出时恢复
struct termios original_termios;

void restore_terminal() {
    tcsetattr(STDIN_FILENO, TCSANOW, &original_termios);
}

void configure_terminal() {
    struct termios new_termios;
    tcgetattr(STDIN_FILENO, &original_termios);
    new_termios = original_termios;
    new_termios.c_lflag &= ~(ICANON | ECHO); // 关闭规范模式和回显
    tcsetattr(STDIN_FILENO, TCSANOW, &new_termios);
}

int kbhit() {
    struct timeval tv = {0, 0};
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(STDIN_FILENO, &fds);
    return select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv) > 0;
}

void DrawNum() {
    // 实现绘制逻辑
    printf("Drawing...\n");
}

int main() {
    configure_terminal();
    atexit(restore_terminal); // 确保程序退出时恢复终端设置

    while (1) {
        if (kbhit()) {
            char ch;
            read(STDIN_FILENO, &ch, 1);
            if (ch == 'q' || ch == 'Q') {
                printf("Exiting the program.\n");
                break;
            }
        }

        // 执行需要定时调用的函数
        // DrawC();
        DrawNum();
        // DrawZh();

        usleep(300 * 1000); // 300毫秒延时
    }

    return 0;
}